package com.flot.yazb.video;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flot.yazb.R;
import com.flot.yazb.base.BActivity;
import com.flot.yazb.base.BApplication;
import com.flot.yazb.SPKeyConfig;
import com.flot.yazb.base.adapter.recycleview.BRAdapter;
import com.flot.yazb.base.adapter.recycleview.RvHolder;
import com.flot.yazb.base.model.BModel;
import com.flot.yazb.aop.stub.CodeStub;
import com.flot.yazb.model.CommentModel;
import com.flot.yazb.model.anchor.AnchorModel;
import com.flot.yazb.model.other.GifeModel;
import com.flot.yazb.model.other.SetModle;
import com.flot.yazb.model.user.UserModel;
import com.flot.yazb.widget.utils.FileAssertUtils;
import com.flot.yazb.widget.utils.GlideImageLoaderUtil;
import com.flot.yazb.widget.utils.IsNullOrEmpty;
import com.flot.yazb.widget.utils.SharedPreferencesUtils;
import com.flot.yazb.widget.utils.ToastUtil;
import com.flot.yazb.widget.GiftView.GiftManage;
import com.flot.yazb.widget.GiftView.SendGiftDialog;
import com.flot.yazb.widget.PayDialog;
import com.flot.yazb.widget.ScrollRecycerView;
import com.flot.yazb.widget.animalView.DivergeView;
import com.flot.yazb.widget.animalView.LoveAnimView;
import com.flot.yazb.widget.player.MediaPlayer;
import com.flot.yazb.widget.vitamioPlayer.PlayVideoPresenterImpl;
import com.flot.yazb.widget.vitamioPlayer.PlayVideoView;
import com.flot.yazb.widget.vitamioPlayer.VideoControllerView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.vov.vitamio.LibsChecker;

/**
 * Created by fengdongfei on 2017/8/27.
 */

public class VideoView extends BActivity implements PlayVideoView {
    private String videoPath = "";
    @BindView(R.id.ic_player)
    MediaPlayer mediaPlayer;
    @BindView(R.id.rl_content)
    RelativeLayout rlContent;
    @BindView(R.id.icon)
    ImageView icon;
    @BindView(R.id.zhuboname)
    TextView zhuboname;
    @BindView(R.id.onlinenum)
    TextView onlinenum;
    @BindView(R.id.atten)
    TextView attened;
    @BindView(R.id.mRecycleview)
    RecyclerView mRecycleview;
    @BindView(R.id.ivclose)
    ImageView ivclose;
    @BindView(R.id.divergeView)
    DivergeView divergeView;
    @BindView(R.id.mrv)
    ScrollRecycerView chatRecycleView;
    @BindView(R.id.edit_message)
    EditText editMessage;
    @BindView(R.id.btn_send_message)
    Button sendMessage;
    @BindView(R.id.ivgift)
    ImageView ivGift;
    @BindView(R.id.animal)
    LinearLayout animal;
    private int[] Clevel = new int[]{
            R.mipmap.rank_1, R.mipmap.rank_2, R.mipmap.rank_3, R.mipmap.rank_4, R.mipmap.rank_5, R.mipmap.rank_6
            , R.mipmap.rank_7, R.mipmap.rank_8, R.mipmap.rank_9, R.mipmap.rank_10, R.mipmap.rank_11, R.mipmap.rank_12, R.mipmap.rank_13
            , R.mipmap.rank_14, R.mipmap.rank_15, R.mipmap.rank_16
            , R.mipmap.rank_17, R.mipmap.rank_18, R.mipmap.rank_19, R.mipmap.rank_20, R.mipmap.rank_21, R.mipmap.rank_22, R.mipmap.rank_23
            , R.mipmap.rank_24, R.mipmap.rank_25, R.mipmap.rank_26
            , R.mipmap.rank_27, R.mipmap.rank_28, R.mipmap.rank_29, R.mipmap.rank_30, R.mipmap.rank_31, R.mipmap.rank_32, R.mipmap.rank_33
            , R.mipmap.rank_34, R.mipmap.rank_35, R.mipmap.rank_36
            , R.mipmap.rank_37, R.mipmap.rank_38, R.mipmap.rank_39, R.mipmap.rank_40, R.mipmap.rank_41, R.mipmap.rank_42, R.mipmap.rank_43
            , R.mipmap.rank_44, R.mipmap.rank_45, R.mipmap.rank_46
            , R.mipmap.rank_47, R.mipmap.rank_48, R.mipmap.rank_49, R.mipmap.rank_50, R.mipmap.rank_51, R.mipmap.rank_52, R.mipmap.rank_53
            , R.mipmap.rank_54, R.mipmap.rank_55, R.mipmap.rank_56
            , R.mipmap.rank_57, R.mipmap.rank_58, R.mipmap.rank_59, R.mipmap.rank_60, R.mipmap.rank_61, R.mipmap.rank_62, R.mipmap.rank_63
            , R.mipmap.rank_64, R.mipmap.rank_65, R.mipmap.rank_66
            , R.mipmap.rank_67, R.mipmap.rank_68, R.mipmap.rank_69, R.mipmap.rank_70, R.mipmap.rank_71, R.mipmap.rank_72, R.mipmap.rank_73
            , R.mipmap.rank_74, R.mipmap.rank_75, R.mipmap.rank_76
            , R.mipmap.rank_77, R.mipmap.rank_78, R.mipmap.rank_79, R.mipmap.rank_80, R.mipmap.rank_81, R.mipmap.rank_82, R.mipmap.rank_83
            , R.mipmap.rank_84, R.mipmap.rank_85, R.mipmap.rank_86
            , R.mipmap.rank_87, R.mipmap.rank_88, R.mipmap.rank_89, R.mipmap.rank_90, R.mipmap.rank_91, R.mipmap.rank_92, R.mipmap.rank_93
            , R.mipmap.rank_94, R.mipmap.rank_95, R.mipmap.rank_96};


    @BindView(R.id.videoControllerView)
    VideoControllerView controllerViewl;

    //----------------
    private boolean isFullScreen = true;
    private AnchorModel anchModel;
    private BRAdapter<AnchorModel> imgAdapter;
    private List<AnchorModel> imgList = new ArrayList();//相册集合
    private static final String[] DEFAULT_PLAYBACK_DOMAIN_ARRAY = {
            "video.baliup.com",
    };
    private PlayVideoPresenterImpl mPresenter;
    private ArrayList<Bitmap> animalList;
    private ScheduledExecutorService scheduledThreadPool_animal;
    private ScheduledExecutorService scheduledThreadPool_comment;
    private int maxMessageList = 150;
    private LinkedBlockingQueue<CommentModel> mChatMessageList = new LinkedBlockingQueue(maxMessageList);
    private List<CommentModel> mChatList = new ArrayList<>();
    private BRAdapter<CommentModel> chatAdapter;
    private UserModel selfModel = BApplication.getInstance().getUserModel();
    private List<String> videoList = new ArrayList<>();
    private SetModle setModel = BApplication.getInstance().getsettModel();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!LibsChecker.checkVitamioLibs(this))
            return;

        setContentView(R.layout.videoview);
        ButterKnife.bind(this);

        anchModel = (AnchorModel) getIntent().getSerializableExtra("anch");

        //-------------------------
        mPresenter = new PlayVideoPresenterImpl(this);
        controllerViewl.setCoverView(anchModel.pic);
        controllerViewl.setONcLoseListener(new VideoControllerView.CloseListener() {
            @Override
            public void close() {
                finish();
            }

            @Override
            public void endZhibo() {
                startPlayId++;
                if ((startPlayId < videoList.size()) && (startPlayId < 7)) {
                    mPresenter.getMedia(videoList.get(startPlayId));
                } else {
                    controllerViewl.endZhibo();
                    finish();
                }
            }
        });

        setScreenFullToggle();

        if (!selfModel.getIsVip()) {
            Map hp = new HashMap<String, Object>();
            hp.put("key", anchModel.id + "");
            List lt = new ArrayList<>();
            lt.add(hp);
            String looked = FileAssertUtils.saveJsonToSDcard(activity, selfModel.id + "_lookTimes.txt", lt);
            switch (looked) {
                case "0":
                    FileAssertUtils.saveJsonToSDcard(activity, selfModel.id + "_lookTimes.txt", lt);
                    initShow();
                    break;
                case "1":
                    initShow();
                    break;
                case "2":
                    PayDialog pa = new PayDialog(VideoView.this, "您已经查看过该房间，开通Vip继续观看");
                    pa.show();
                    pa.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            finish();
                        }
                    });
                    break;
                case "3":
                    PayDialog dialog = new PayDialog(VideoView.this, "查看房间数达到最大，开通Vip继续观看");
                    dialog.show();
                    dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            finish();
                        }
                    });
                    break;
            }
        } else {
            initShow();
        }
    }

    private void initShow() {
        initHeadAdapter();
        getAnchMsg();
        getHeadImgs();

        getUserMsg();

        cresteXinAnimal();
        scheduledThreadPool_animal = Executors.newScheduledThreadPool(5);
        scheduledThreadPool_animal.scheduleAtFixedRate(new Runnable() {
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        startAnim();
                    }
                });
            }
        }, 1, 1, TimeUnit.SECONDS);

        initChatAdapter();

        //循环获取评论
        scheduledThreadPool_comment = Executors.newScheduledThreadPool(15);
        scheduledThreadPool_comment.scheduleAtFixedRate(new Runnable() {
            public void run() {
                getComment();
            }
        }, 1, 10, TimeUnit.SECONDS);
    }

    private void getUserMsg() {
        String id = SharedPreferencesUtils.getString(VideoView.this, SPKeyConfig.USERID, "");
        UserModel.getUserMsg(id, new BModel.Transit<UserModel>(VideoView.this) {
            @Override
            public void onBorn(UserModel serializable, String code, String message) {
                if (code.equals(CodeStub.B_OK)) {
                    BApplication.getInstance().setUserModel(serializable);
                    SharedPreferencesUtils.saveString(VideoView.this, SPKeyConfig.USERID, serializable.id);
                    selfModel = BApplication.getInstance().getUserModel();
                }
                if (selfModel.getIsVip() == true) {
                    getVipSpList();
                } else {
                    geiSpList();
                }
            }
        });
    }

    private void getVipSpList() {
        AnchorModel.getvipUrl(new BModel.Transit<AnchorModel[]>(this) {
            @Override
            public void onBorn(AnchorModel[] serializable, String code, String message) {
                if (code.equals(CodeStub.B_OK)) {
                    if (serializable != null) {
                        for (AnchorModel url : serializable) {
                            videoList.add(url.url);
                        }
                        mPresenter.getMedia(videoList.get(startPlayId));
                    }
                } else {
                }
            }
        });
    }

    private void initChatAdapter() {
        chatRecycleView.setLayoutManager(new LinearLayoutManager(activity));
        chatAdapter = new BRAdapter<CommentModel>(this, R.layout.activity_chat_item, mChatList) {
            public int lev = 1;

            @Override
            protected void convert(RvHolder holder, CommentModel chatModel, int position) {
                holder.setText(R.id.txt_chat_name, chatModel.username);
                holder.setText(R.id.txt_chat_message, chatModel.content);
                if (!IsNullOrEmpty.isEmpty(chatModel.rank) && !"0".equals(chatModel.rank)) {
                    lev = Integer.parseInt(chatModel.rank);
                    if (lev >= Clevel.length) {
                        lev = 1;
                    }
                } else {
                    lev = 1;
                }
                holder.setBackgroundRes(R.id.img_chat_level, Clevel[lev - 1]);
            }
        };
        chatRecycleView.setAdapter(chatAdapter);

        chatHandle.sendEmptyMessageDelayed(0, 2000);

        giftHandle.sendEmptyMessageDelayed(0, 3000);
    }

    private void initHeadAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecycleview.setLayoutManager(linearLayoutManager);
        imgAdapter = new BRAdapter<AnchorModel>(this, R.layout.activity_img_item_circle, imgList) {
            @Override
            protected void convert(RvHolder holder, AnchorModel imgsModel, int position) {
                GlideImageLoaderUtil.loadImage((ImageView) holder.getView(R.id.pic), imgsModel.headpic, R.mipmap.activity_splash_background);
            }
        };
        mRecycleview.setAdapter(imgAdapter);
    }

    private Handler chatHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mChatMessageList.size() > 0)
                mChatList.add(mChatMessageList.poll());

            chatAdapter.notifyDataSetChanged();

            if (mChatList.size() > 0)
                chatRecycleView.smoothScrollToPosition(mChatList.size() - 1);

            chatHandle.sendEmptyMessageDelayed(0, 2500);

        }
    };

    private Handler giftHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mChatMessageList.size() > 0) {
                CommentModel bean = mChatMessageList.poll();
                createGift(bean);
            }
            giftHandle.sendEmptyMessageDelayed(0, 5000);
        }
    };

    private GiftManage giftManger;

    private void createGift(CommentModel bean) {
        if (giftManger == null)
            giftManger = new GiftManage(activity, animal);
        GifeModel vo = new GifeModel();
        Random random = new Random();
        int x = random.nextInt(8);
        vo.gift_id = x + "";
        vo.msg = SendGiftDialog.names[x];
        vo.num = 1;
        vo.thumb = bean.headpic;
        vo.name = bean.username;
        giftManger.addGift(vo);
        giftManger.showGift();
    }

    private void getComment() {
        CommentModel.getComment(new BModel.Transit<CommentModel[]>(this) {
            @Override
            public void onBorn(CommentModel[] serializable, String code, String message) {
                if (mChatMessageList == null) {
                    return;
                }
                try {
                    mChatMessageList.addAll(Arrays.asList(serializable));
                }catch (Exception e){

                }
            }
        });
    }

    private int startPlayId = 0;

    private void geiSpList() {
        AnchorModel.getUrl(new BModel.Transit<AnchorModel[]>(this) {
            @Override
            public void onBorn(AnchorModel[] serializable, String code, String message) {
                if (code.equals(CodeStub.B_OK)) {
                    if (serializable != null) {
                        for (AnchorModel url : serializable) {
                            videoList.add(url.url);
                        }
                        mPresenter.getMedia(videoList.get(startPlayId));
                    }
                } else {
                }
            }
        });
    }

    private void getAnchMsg() {
        AnchorModel.getDetail(anchModel.id, new BModel.Transit<AnchorModel>(this) {
            @Override
            public void onBorn(AnchorModel serializable, String code, String message) {
                if (code.equals(CodeStub.B_OK)) {
                    GlideImageLoaderUtil.loadImage(icon, serializable.pic, R.mipmap.activity_splash_background);
                    zhuboname.setText(serializable.name);
                    onlinenum.setText(serializable.hit);
                } else {
                }

            }
        });
    }

    private void getHeadImgs() {
        AnchorModel.getHeadImgs(new BModel.Transit<AnchorModel[]>(this) {
            @Override
            public void onBorn(AnchorModel[] serializable, String code, String message) {
                if (code.equals(CodeStub.B_OK)) {
                    imgList.clear();
                    imgList.addAll(Arrays.asList(serializable));
                    imgAdapter.notifyDataSetChanged();
                }
            }
        });
    }


    @Override
    protected void onStart() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (controllerViewl != null)
            controllerViewl.release();

        if (animalList != null) {
            animalList.clear();
            animalList = null;
        }

        if (scheduledThreadPool_animal != null)
            scheduledThreadPool_animal.shutdownNow();

        if (scheduledThreadPool_comment != null)
            scheduledThreadPool_comment.shutdownNow();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void setScreenFullToggle() {

        int flag = activity.getWindow().getAttributes().flags;
        if ((flag & WindowManager.LayoutParams.FLAG_FULLSCREEN)
                == WindowManager.LayoutParams.FLAG_FULLSCREEN) {
            this.getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            this.getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isFullScreen) {
                return true;
            } else {
                return super.onKeyDown(keyCode, event);
            }

        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @OnClick({R.id.atten, R.id.ivclose, R.id.btanimal, R.id.btn_send_message, R.id.ivgift})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.atten:
                ToastUtil.showToast(activity, "关注成功");
                attened.setText("已关注");
                onlinenum.setText((Integer.parseInt(onlinenum.getText().toString()) + 1) + "");
                attened.setEnabled(false);
                attened.setClickable(false);
                break;
            case R.id.ivclose:
                controllerViewl.pause();
                controllerViewl.release();
                finish();
                break;
            case R.id.btanimal:
                if (mIndex == 5) {
                    mIndex = 0;
                }
                divergeView.startDiverges(mIndex);
                mIndex++;
                break;
            case R.id.btn_send_message:
                if ("".equals(editMessage.getText().toString())) {
                    return;
                }
                String sc = editMessage.getText().toString();
                CommentModel mcModel = createCommentModel(sc);
                mChatList.add(mcModel);
                chatAdapter.notifyDataSetChanged();
                chatRecycleView.smoothScrollToPosition(mChatList.size() - 1);
                editMessage.setText("");
                break;
            case R.id.ivgift:
                SendGiftDialog giftDialog = new SendGiftDialog(activity, animal);
                giftDialog.show();
                ;
                break;
        }
    }

    private CommentModel selfCommentModel;

    private CommentModel createCommentModel(String sc) {
        if (selfCommentModel == null) {
            selfCommentModel = new CommentModel();
        }
        selfCommentModel.content = sc;
        selfCommentModel.headpic = selfModel.avatar;
        selfCommentModel.rank = selfModel.rank;
        selfCommentModel.username = selfModel.nicheng;
        return selfCommentModel;
    }

    @Override
    public void setLinkUrl(String url) {
        controllerViewl.setVideoPath(url);
        controllerViewl.start();
    }

    @Override
    public void closeParentActivity() {
        controllerViewl.endZhibo();
    }

    public void startAnim() {
        int x = screenWidth / 2 + 100;
        int y = screenHeight / 2 - 60;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        LoveAnimView loveAnimView = new LoveAnimView(this);
        loveAnimView.setLayoutParams(params);
        loveAnimView.setStartPosition(new Point(x, y));
        loveAnimView.setEndPosition(new Point(x - (int) (Math.random() * 200), y - ((int) (Math.random() * 500) + 200)));
        loveAnimView.startLoveAnimation();
        rlContent.addView(loveAnimView);
    }


    private int mIndex = 0;

    public void cresteXinAnimal() {
        animalList = new ArrayList<>();
        animalList.add(((BitmapDrawable) ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_praise_sm1, null)).getBitmap());
        animalList.add(((BitmapDrawable) ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_praise_sm2, null)).getBitmap());
        animalList.add(((BitmapDrawable) ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_praise_sm3, null)).getBitmap());
        animalList.add(((BitmapDrawable) ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_praise_sm4, null)).getBitmap());
        animalList.add(((BitmapDrawable) ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_praise_sm5, null)).getBitmap());
        animalList.add(((BitmapDrawable) ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_praise_sm6, null)).getBitmap());


        divergeView.post(new Runnable() {
            @Override
            public void run() {
                divergeView.setEndPoint(new PointF(divergeView.getMeasuredWidth() / 2, 0));
                divergeView.setDivergeViewProvider(new Provider());
            }
        });
    }


    class Provider implements DivergeView.DivergeViewProvider {

        @Override
        public Bitmap getBitmap(Object obj) {
            return animalList == null ? null : animalList.get((int) obj);
        }
    }

}
